<!--
 * @Author: mayijun
 * @Date: 2022-07-19 15:21:58
 * @LastEditors: mayijun
 * @LastEditTime: 2022-08-11 14:22:06
-->
<script lang="ts" setup>
import { PropType, reactive, ref, watch } from 'vue';
import StatPeriod from '@/views/indexDevelop/develop/components/statPeriod/index.vue';
import BusinessLine from '@/views/indexDevelop/develop/components/businessLine/index.vue';
import API from '@/services';
import _ from 'lodash';
import { IBusinessLimit } from '@/constants/indexDevelop';
import { Modal } from '@arco-design/web-vue';
import { useRoute } from 'vue-router';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  drawerTitle: {
    type: String,
    default: ''
  },
  metricsOptions: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  deriveModel: {
    type: Object as PropType<defs.DerivedDevelopDto>,
    default: () => {}
  },
  derivedDevelopFactor: {
    type: Object as PropType<defs.DerivedDevelopFactorDto>,
    default: () => {}
  },
  metricsFilter: {
    type: Object as PropType<defs.MetricsFilterDto>,
    default: () => {}
  },
  periodList: {
    type: Array as PropType<any[]>,
    default: () => []
  }
});
const emit = defineEmits(['update:visible', 'getDimensionList', 'updateNode']);

//上线状态
const route = useRoute();
let status = ref<any>(route.query.status);

const state = reactive({
  modelOptions: [] as any[], //模型列表
  isStatPeriodSelect: false,
  isBusinessLineSelect: false,
  metricsType: '',
  oldMetricsId: 0,
  oldModelId: 0
});

let ruleFormRef = ref();
//指标因子对象
const derivedDevelopFactor = ref<defs.DerivedDevelopFactorDto>({});
//业务范围对象
const businessLimit = ref<IBusinessLimit>({
  countTypeDto: {
    begin: 0,
    countType: 0,
    countWay: '',
    end: 0,
    filterValue: ''
  } as defs.CountTypeDto,
  tableFieldColumn: '',
  tableFieldName: '',
  type: 'and',
  isRoot: true,
  compontType: 2,
  children: []
});
//最大层级
const treeMax = ref({ num: 1 });

//确定提交
const handleOk = () => {
  ruleFormRef.value.validate((valid: any) => {
    if (!valid) {
      props.derivedDevelopFactor.factorName =
        derivedDevelopFactor.value.factorName;
      props.derivedDevelopFactor.metricsId =
        derivedDevelopFactor.value.metricsId;
      props.derivedDevelopFactor.modelId = derivedDevelopFactor.value.modelId;
      //统计周期
      if (props.metricsFilter.ifGroupBy == 0 && state.isStatPeriodSelect) {
        props.derivedDevelopFactor.countCycleDto =
          derivedDevelopFactor.value.countCycleDto;
      }

      //业务范围处理
      if (state.isBusinessLineSelect) {
        let bs = _.cloneDeep(businessLimit.value);
        businessLimitValue(bs);
        props.derivedDevelopFactor.limitDto = bs;
      } else {
        props.derivedDevelopFactor.limitDto = null as any;
      }
      //更新计算规则指标节点
      emit('updateNode');
      emit('update:visible', false);
    }
  });
};
const handleCancel = () => {
  emit('update:visible', false);
};

//指标改变事件
const metricsChange = (val: any) => {
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '确定切换指标？',
    content: '切换指标将使已配置好的“模型和业务限定”清空',
    simple: false,
    closable: true,
    okText: '确定切换',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      let obj = props.metricsOptions.find((item) => item.id == val);
      state.metricsType == obj.metricsType;
      //清空模型
      derivedDevelopFactor.value.modelId = undefined;
      derivedDevelopFactor.value.limitDto = undefined;
      derivedDevelopFactor.value.countCycleDto = undefined;
      state.isStatPeriodSelect = false;
      state.isBusinessLineSelect = false;
      //设置统计周期
      setTimeframe(val);
      done(true);
    },
    onBeforeCancel: () => {
      derivedDevelopFactor.value.metricsId = state.oldMetricsId;
      return true;
    }
  });
};
//设置统计周期
const setTimeframe = async (metricsId: any) => {
  await getModelList(metricsId);
  emit('getDimensionList', metricsId, derivedDevelopFactor.value.modelId);
};

//指标下拉框打开时
const metricsVisible = (val: boolean) => {
  if (val) {
    //保存原来的值
    if (derivedDevelopFactor.value.metricsId) {
      state.oldMetricsId = derivedDevelopFactor.value.metricsId;
    }
  }
};

//模型改变事件
const modelChange = (val: any) => {
  if (state.oldModelId != 0) {
    Modal.confirm({
      modalClass: 'model-message-confirm',
      title: '确定切换模型？',
      content: '切换指标将使已配置好的“业务限定”清空',
      simple: false,
      closable: true,
      okText: '确定切换',
      okButtonProps: {
        style: {
          backgroundColor: '#FF1A3B'
        }
      },
      onBeforeOk: (done) => {
        derivedDevelopFactor.value.limitDto = undefined;
        state.isBusinessLineSelect = false;
        state.isStatPeriodSelect = false;
        derivedDevelopFactor.value.countCycleDto = undefined;
        emit('getDimensionList', derivedDevelopFactor.value.metricsId, val);
        done(true);
      },
      onBeforeCancel: () => {
        derivedDevelopFactor.value.modelId = state.oldModelId;
        return true;
      }
    });
  } else {
    emit('getDimensionList', derivedDevelopFactor.value.metricsId, val);
  }
};

const periodUnit = (val?: string) => {
  if (val == 'same_day') {
    return 'day';
  } else if (val == 'same_week') {
    return 'week';
  } else if (val == 'same_month') {
    return 'month';
  } else if (val == 'same_quarter') {
    return 'quarter';
  } else if (val == 'same_year') {
    return 'year';
  }
};

//模型下拉框打开时
const modelVisible = (val: boolean) => {
  if (val) {
    //保存原来的值
    if (derivedDevelopFactor.value.modelId) {
      state.oldModelId = derivedDevelopFactor.value.modelId;
    }
  }
};

//获取模型列表
const getModelList = async (id: any) => {
  const { code, data } = await API.dataModel.getGetDevelopMetricsModelListById({
    id
  });
  if (code == 200 && Array.isArray(data)) {
    state.modelOptions = data;
    //默认第一个
    if (state.modelOptions.length > 0) {
      derivedDevelopFactor.value.modelId = state.modelOptions[0].id;
    }
  }
};
//统计周期校验
const validateCountCycle = (value: any, callback: any) => {
  if (!state.isStatPeriodSelect) {
    callback('请添加统计周期');
  }
  callback();
};

//业务范围数据处理
const businessLimitValue = (limit: any) => {
  delete limit.isRoot;
  delete limit.compontType;
  if (limit.countTypeDto && limit.countTypeDto.filterValue) {
    if (Array.isArray(limit.countTypeDto.filterValue)) {
      limit.countTypeDto.filterValue =
        limit.countTypeDto?.filterValue.join(',');
    }
  } else {
    limit.children?.map((item: any) => {
      businessLimitValue(item);
    });
  }
};

//详情业务范围数据处理
const detailBusinessLimitValue = (limit: any, isRoot: boolean) => {
  limit.isRoot = isRoot;
  if (!limit.isRoot && limit.children && limit.children.length > 0) {
    limit.compontType = 1;
  } else {
    limit.compontType = 2;
  }

  if (limit.countTypeDto && limit.countTypeDto.filterValue) {
    if (limit.countTypeDto.filterValue) {
      limit.countTypeDto.filterValue =
        limit.countTypeDto?.filterValue.split(',');
    }
  } else {
    limit.children?.map((item: any) => {
      detailBusinessLimitValue(item, false);
    });
  }
};

//回显
watch(
  () => props.visible,
  (val) => {
    if (val) {
      derivedDevelopFactor.value = _.cloneDeep(props.derivedDevelopFactor);
      getModelList(derivedDevelopFactor.value.metricsId);
      //统计周期
      if (derivedDevelopFactor.value.countCycleDto) {
        state.isStatPeriodSelect = true;
      }
      //业务范围处理
      if (
        derivedDevelopFactor.value.limitDto &&
        JSON.stringify(derivedDevelopFactor.value.limitDto) != '{}'
      ) {
        let bs = _.cloneDeep(derivedDevelopFactor.value.limitDto);
        detailBusinessLimitValue(bs, true);
        businessLimit.value = bs;
        state.isBusinessLineSelect = true;
      } else {
        businessLimit.value = {
          countTypeDto: {
            begin: 0,
            countType: 0,
            countWay: '',
            end: 0,
            filterValue: ''
          } as defs.CountTypeDto,
          tableFieldColumn: '',
          tableFieldName: '',
          type: 'and',
          isRoot: true,
          compontType: 2,
          children: []
        };
        state.isBusinessLineSelect = false;
      }
      emit(
        'getDimensionList',
        derivedDevelopFactor.value.metricsId,
        derivedDevelopFactor.value.modelId
      );
    }
  }
);

watch(
  () => props.metricsFilter,
  (val) => {
    if (val) {
      console.log(props.derivedDevelopFactor);
      //状态是0，统计周期默认值处理
      if (status != 1 && props.metricsFilter.ifGroupBy == 0 && !props.derivedDevelopFactor.countCycleDto) {
        let obj = props.periodList.find(
          (item) => item.value.indexOf(props.metricsFilter.timeframe) != -1
        );
        derivedDevelopFactor.value.countCycleDto = {};
        if (obj) {
          derivedDevelopFactor.value.countCycleDto.type = obj.value;
          derivedDevelopFactor.value.countCycleDto.unit =
            props.metricsFilter.timeframe;
        } else {
          derivedDevelopFactor.value.countCycleDto.type =
            props.periodList[0].value;
          derivedDevelopFactor.value.countCycleDto.unit = periodUnit(
            props.periodList[0].value
          );
        }
        state.isStatPeriodSelect = true;
      }
    }
  }
);
</script>
<template>
  <a-drawer
    :visible="props.visible"
    :width="904"
    @ok="handleOk"
    @cancel="handleCancel"
    class="mertrics-drawer"
    unmountOnClose
  >
    <template #title>
      {{ props.drawerTitle }}
    </template>
    <a-form
      ref="ruleFormRef"
      :model="derivedDevelopFactor"
      :label-col-props="{ span: 3, offset: 0 }"
    >
      <a-form-item
        field="factorName"
        label="因子名称"
        validate-trigger="input"
        :show-colon="true"
        :rules="[{ required: true, message: '请输入因子名称' }]"
      >
        <a-input
          :disabled="status == 1"
          v-model="derivedDevelopFactor.factorName"
          placeholder="请输入"
          :style="{ width: '372px' }"
        />
      </a-form-item>
      <a-form-item
        field="metricsId"
        label="指标"
        :show-colon="true"
        :rules="[{ required: true, message: '请选择指标' }]"
      >
        <a-select
          :disabled="status == 1"
          :options="props.metricsOptions"
          v-model="derivedDevelopFactor.metricsId"
          :field-names="{ value: 'id', label: 'cnName' }"
          placeholder="请选择"
          :style="{ width: '372px' }"
          @change="metricsChange"
          @popup-visible-change="metricsVisible"
        >
        </a-select>
      </a-form-item>
      <a-form-item
        field="modelId"
        label="模型"
        :show-colon="true"
        :rules="[{ required: true, message: '请选择模型' }]"
      >
        <a-select
          :disabled="status == 1"
          :options="state.modelOptions"
          v-model="derivedDevelopFactor.modelId"
          :field-names="{ value: 'id', label: 'modelName' }"
          placeholder="请选择"
          :style="{ width: '372px' }"
          @change="modelChange"
          @popup-visible-change="modelVisible"
        >
        </a-select>
      </a-form-item>
      <a-form-item
        field="countCycleDto"
        label="统计周期"
        :show-colon="true"
        :rules="[{ required: true, validator: validateCountCycle }]"
        v-if="props.metricsFilter.ifGroupBy == 0"
      >
        <StatPeriod
          v-model:isStatPeriodSelect="state.isStatPeriodSelect"
          :countDateType="props.metricsFilter.timeframe"
          :deriveModel="props.deriveModel"
          :countCycle="derivedDevelopFactor.countCycleDto"
          :isFast="false"
          :isRequired="true"
        ></StatPeriod>
      </a-form-item>
      <a-form-item
        field="countCycleDto"
        label="统计周期"
        :show-colon="true"
        v-if="props.metricsFilter.ifGroupBy == 1"
      >
        <span v-if="props.metricsFilter.timeframe == 'day'">当日</span>
        <span v-else-if="props.metricsFilter.timeframe == 'week'">当周</span>
        <span v-else-if="props.metricsFilter.timeframe == 'month'">当月</span>
        <span v-else-if="props.metricsFilter.timeframe == 'quarter'">当季</span>
        <span v-else-if="props.metricsFilter.timeframe == 'year'">当年</span>
        <span v-else>-</span>
      </a-form-item>
      <a-form-item
        field="limitDto"
        label="业务限定"
        :show-colon="true"
        content-class="business-line"
      >
        <BusinessLine
          :businessLimit="businessLimit"
          :modelTableColumnList="props.metricsFilter.queryFieldList"
          v-model:isBusinessLineSelect="state.isBusinessLineSelect"
          :treeMax="treeMax"
        ></BusinessLine>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>
<style lang="scss">
.mertrics-drawer {
  .arco-drawer-body {
    padding-left: 0;
  }
  .business-line {
    .tree-node-div {
      margin-left: -6px;
    }
  }
}
</style>